package com.breaktian.assemble.security.des;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * Created by keke.tian on 2018/4/24.
 */

public class ThreeDesUtil {

    // 算法名称
    private static final String KEY_ALGORITHM = "desede";
    // 加解密算法/模式/填充方式
    private static final String algorithmStr = "desede/ECB/PKCS5Padding";

    //初始化向量
    static final byte[] IV = { 0x10, 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x55, 0x50, 0x66, 0x77, 0x68, 0x37, 0x30, 0x38 };

    //24个字节的密钥key
    static byte[] KEY = { 0x13, 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x55, 0x50, 0x66, 0x77, 0x68, 0x37, 0x30, 0x37, 0x55, 0x50, 0x66, 0x77, 0x68, 0x37, 0x30, 0x37 };


    public static void main(String[] args) throws Exception {
//        // 待加密内容
//        String str = "测试内容，woai祖瑶瑶woaiwoai祖瑶瑶woaiwoai祖瑶瑶woaiwoai祖瑶瑶woai";
//        String encryptStr = encrypt(str, KEY);
//        System.out.println("encryptStr:"+encryptStr);
//        String decryptStr = decrypt(encryptStr,KEY);
//        System.out.println("decryptStr:"+decryptStr);
//        str = str.replace("woai","woxiang");
//        System.out.println(str);

        byte a = -123;
        int r = (int)(a&0xff);
        System.out.println(r);
    }

    public static String encrypt(String content,byte[] key){
        String result = "";
        try {
            byte[] encryptByte = encrypt(content.getBytes(),key);
            result = parseByte2HexStr(encryptByte);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static String decrypt(String content,byte[] key){
        String result = "";
        try {

            byte[] decryptByte = parseHexStr2Byte(content);
            result = new String(decrypt(decryptByte,key));
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    /**
     * ECB加密,不要IV
     * @param key 密钥
     * @param data 明文
     * @return Base64编码的密文
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key)
            throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance(algorithmStr);
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }
    /**
     * ECB解密,不要IV
     * @param key 密钥
     * @param data Base64编码的密文
     * @return 明文
     * @throws Exception
     */
    public static byte[] decrypt( byte[] data, byte[] key)
            throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance(algorithmStr);
        cipher.init(Cipher.DECRYPT_MODE, deskey);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }
    /**
     * CBC加密
     * @param key 密钥
     * @param iv IV
     * @param data 明文
     * @return Base64编码的密文
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key, byte[] iv)
            throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance(algorithmStr);
        IvParameterSpec ips = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }
    /**
     * CBC解密
     * @param key 密钥
     * @param iv IV
     * @param data Base64编码的密文
     * @return 明文
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key, byte[] iv)
            throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance(algorithmStr);
        IvParameterSpec ips = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }


    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);//&0xFF 这样做的目的就是为了保证二进制数据的一致性(https://blog.csdn.net/iblade/article/details/73289831)
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
